<template>
  <div :class="['provider-list', 'common-list-container__v2', {'mar-r-12': isLogOut}]">
    <div class="provider-list-main">
      <!--搜索Start-->
      <div ref="tableHeaderContainer" :class="['provider-list-main-search', 'flex', {'flexEnd': isLogOut}]">
        <div v-if="!isLogOut"  class="provider-list-main-search-btn flex-x">
          <el-button
            type="primary"
            v-if="btnsPermission['create']"
            @click="gotoUrl('PageServiceProviderCreate')">{{$t('common.pageTitle.pageServiceProviderCreate')}}</el-button>
          <!-- TODO -->
          <el-button type="plain-third" @click="bulkAllocation(true)">{{$t('serviceProvider.accountTip.tip18')}}</el-button>
        </div>
        <div class="flex-x">
          <!-- <biz-remote-select v-model="label" :remote-method="getAllLabel" :placeholder="$t('common.placeholder.select')" clearable @input="searchList"/> -->
          <el-input
            class="search-input mar-r-12 mar-l-12 input-with-append-search"
            v-model="deptKeyword"
            :placeholder="$t('common.placeholder.inputServiceProviderCodeName')"
            v-trim:blur
            @keyup.enter.native="searchList">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
            <el-button
              type="primary"
              slot="append"
              @click="onSearch"
              v-track="$track.formatParams('KEYWORD_SEARCH')"
              native-type="submit">
              {{$t('common.base.search')}}
            </el-button>
          </el-input>
          <el-button type="plain-third" @click="handleReset" v-track="$track.formatParams('RESET_SEARCH')">{{$t('common.base.reset')}}</el-button>
          <!-- 高级搜索 -->
          <div :class="['advanced-search-wrap', 'bg-w']">
            <advanced-search
              :fields="searchFieldInfo"
              :search-model="viewportSearchModel"
              :has-create="false"
              :has-save="false"
              :in-common-use="inCommonUse"
              @changeCommonUse="changeCommonUse"
              @search="handleAdvancedSearch"
            />
          </div>
          <el-dropdown v-if="!isLogOut && (btnsPermission.batchEdit || btnsPermission.batchDelete)">
            <div class="cur-point">
              <span>{{$t('common.base.moreOperator')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
            <el-dropdown-menu slot="dropdown" class="el-dropdown-provider">
              <el-dropdown-item >
                <div @click="openDialog('importProviderList')" v-if="btnsPermission['providerImport']">{{$t('common.base.import')}}</div>
              </el-dropdown-item>
              <el-dropdown-item >
                <div @click="openDialog('updateProviderList')" v-if="btnsPermission['batchEdit']">{{$t('common.base.batchUpdate')}}</div>
              </el-dropdown-item>
              <el-dropdown-item >
                <div @click="exportProcider(false)" v-if="btnsPermission['providerExport']">{{$t('common.base.export')}}</div>
              </el-dropdown-item>
              <el-dropdown-item >
                <div @click="exportProcider(true)" v-if="btnsPermission['providerExport']">{{$t('common.base.exportAll')}}</div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div v-if="btnsPermission['batchEdit']" @click="editProviders">{{$t('common.base.bulkEdit')}}</div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div v-if="btnsPermission['batchDelete']" @click="batchStopProvider">{{$t('common.base.batchLogout')}}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div class="el-dropdown cur-point mar-l-8" @click="handleSelectColumn">
          {{$t('common.base.choiceCol')}}
          <i class="iconfont icon-fdn-select"></i>
          </div>
        </div>
      </div>
      <!--搜索End-->

      <!--表格Start-->
      <div class="account-list-table mar-t-16">
        <el-table
          v-table-style
          ref="tableRef"
          v-loading="listLoading"
          header-row-class-name="common-list-table-header__v2"
          :data="tableData"
          border
          stripe
          class="bbx-normal-list-box"
          :height="tableContainerHeight"
          @select="handleSelection"
          @select-all="handleSelection"
        >
          <template slot="empty">
            <BaseListForNoData
              v-show="!listLoading"
              :notice-msg="$t('common.base.tip.noData')"
            ></BaseListForNoData>
          </template>
          <el-table-column
            v-if="!isLogOut"
            type="selection"
            width="48"
            align="center"
            class-name="select-column"
          ></el-table-column>
          <template v-for="column in columns">
            <el-table-column
              v-if="column && column.show"
              :show-overflow-tooltip="column.showTip"
              :key="column.fieldName"
              :label="column.displayName"
              :min-width="column.minWidth"
              :prop="column.fieldName"
              :width="column.width"
              :resizable="true"
              :fixed="column.fixLeft || false"
            >
              <template slot-scope="scope">
                <!--服务商名称-->
                <template v-if="column.fieldName === 'providerName'">
                  <div
                    class="c-primary cur-point"
                    @click="gotoUrl(
							          'PageServiceProviderDetail',
							            scope.row.tenantProviderId ,
							          `id=${scope.row.tenantProviderId}`)">
                    {{ scope.row.providerName }}
                  </div>
                </template>
                <!--联系地址-->
                <template v-else-if="column.fieldName === 'providerAddress'">
                  {{ scope.row[column.fieldName] | fmt_address }}
                </template>
                <!--状态-->
                <template v-else-if="column.fieldName === 'status'">
                  <div>{{ getStatus(scope.row.status) }}</div>
                </template>
                <!--授权区域-->
                <template v-else-if="column.fieldName === 'authorizeAddress'">
                  {{ getAreas(scope.row[column.fieldName])}}
                </template>
                <!--授权有效期-->
                <template v-else-if="column.fieldName === 'validTime'">
                  <div v-if="scope.row[column.fieldName]">{{ scope.row[column.fieldName].validTime | fmt_date }} 至 {{ scope.row[column.fieldName].inalidTime | fmt_date }}</div>
                </template>
                <!--角色名称-->
                <template v-else-if="column.fieldName === 'role'">
                 <div v-if="scope.row[column.fieldName]"> {{ scope.row[column.fieldName].name }}</div>
                </template>
                <!--授权工单类型&授权产品类型-->
                <template v-else-if="column.fieldName === 'authorizeTask' || column.fieldName === 'authorizeProduct'">
                  {{ getAuthorize(scope.row[column.fieldName])}}
                </template>
                <!-- 创建人&更新人 -->
                <template v-else-if="column.fieldName === 'createUser' || column.fieldName === 'updateUser'">
                  <div v-if="scope.row[column.fieldName]">{{ scope.row[column.fieldName].displayName || '' }}</div>
                </template>
                <!-- 创建时间&更新时间-->
                <template v-else-if="column.fieldName === 'createTime' || column.fieldName === 'updateTime'">
                  {{ scope.row[column.fieldName] | fmt_datetime }}
                </template>
                <template v-else-if="column.fieldName === 'qualificationNames'">
                  {{ scope.row.qualificationNames && scope.row.qualificationNames.join('，')}}
                </template>
                <template v-else-if="column.fieldName === 'imageDisplay'">
                  <div class="flex-x goods-img-list" style="height:100%">
                    <img
                      class="cur-point mar-r-8"
                      v-for="item in scope.row[column.fieldName]"
                      :key="item.id"
                      :src="`${item.url}?x-oss-process=image/resize,m_fill,h_32,w_32`"
                      @click.stop="previewImg(item.url,scope.row.imageDisplay)"/>
                  </div>
                </template>
                <template v-else-if="column.fieldName === 'accountNum'">
                  <div v-if="scope.row[column.fieldName]">{{ scope.row[column.fieldName] }}</div>
                </template>
                <!-- 富文本 -->
                <template v-else-if="column.formType === 'richtext'">
                  <div class='view-detail-btn' @click.stop="openRichtextVisible(scope.row, column)">
                    <span v-if="scope.row.formVOList && scope.row.formVOList[column.field]">{{$t('common.base.view')}}</span>
                  </div>
                </template>

                <template v-else>
                  {{
                    $formatFormField(column, scope.row, 'formVOList')
                  }}
                </template>
              </template>
            </el-table-column>
          </template>
          <el-table-column v-if="isLogOut" :label="$t('common.base.operation')" width="130px" fixed="right">
            <template slot-scope="scope">
              <div
                v-if="btnsPermission['remove']"
                @click="deleteProvider(scope.row)">
                <span class="c-primary cur-point">{{$t('common.base.delete')}}</span>
              </div>
              <div v-if="btnsPermission['restore']"  @click="recoveryProvider(scope.row)">
                <span class="c-primary cur-point mar-l-12">{{$t('common.button.recover')}}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 Start -->
        <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer">
          <div class="list-info">
            <i18n path="common.base.table.totalCount" tag="span">
              <span place="count" class="level-padding">{{ page.total }}</span>
            </i18n>
            <template v-if="multipleSelection && multipleSelection.length>0">
              <i18n path="common.base.table.selectedNth">
                <span place="count" class="color-primary pad-l-5 pad-r-5">{{ multipleSelection.length }}</span>
              </i18n>
              <span class="color-primary cur-point" @click="toggleClearSelection">{{$t('common.base.clear')}}</span>
            </template>
          </div>
          <el-pagination
            background
            @current-change="handlePageJump"
            @size-change="handleSizeChange"
            :page-sizes="defaultTableData.defaultPageSizes"
            :page-size="page.pageSize"
            :current-page="page.pageNum"
            layout="prev, pager, next, sizes, jumper"
            :total="page.total"
          >
          </el-pagination>
        </div>
        <!-- 分页 End -->
      </div>
      <!--表格End-->

      <!-- 选择列Start -->
      <biz-select-column ref="advanced" mode="provider" @save="saveColumnStatus" />
      <!-- 选择列End-->

      <!-- 批量编辑 -->
      <provider-batch-edit-dialog
        ref="providerBatchEditDialog"
        :config="{
          fields: batchEditProviderTemplateFields,
          type: 'notOrder'
        }"
        :selected-ids="selectedIds"
        @update="resetSearch"
      ></provider-batch-edit-dialog>

      <!--批量分配-->
      <provider-account ref="providerAccount" @refresh="resetSearch"/>
    </div>
    <!-- start 导入 -->
    <base-import :title="$t('common.base.importProvider')" ref="importModal" :action="providerBaseImportFile" :uploadParamObject="uploadParamObject">
      <div slot="tip">
        <div class="base-import-warn">
          <i18n path="common.base.importModal.downloadTemplateTip">
            <a :href="`${providerBaseImportTemplate}?type=1`" place="link">{{$t('common.base.importModal.importTemplate')}}</a>
          </i18n>
        </div>
      </div>
    </base-import>
    <!-- end 导入 -->

    <!-- start 批量更新 -->
    <biz-batch-update
      ref="batchUpdateDialog"
      :selected-ids="selectedIds"
      :total-items="page.total"
      :uploadParamObject="uploadParamObject"
      :batch-update-template="batchUpdateUrlTemplate"
      :build-download-params="buildSearchParams"
      :isPostBatch="true"
      :action="providerOrEngineerUpdateBatch"
      :title="$t('component.bizBatchUpdate.providerTitle')"
      :moduleTitle="$t('common.base.serviceProvider')"
      @success="search"
    ></biz-batch-update>
    <!-- end 批量更新 -->

    <base-export
      ref="exportPanel"
      :columns="exportColumns"
      :build-params="buildExportParams"
      :validate="checkExportCount"
      :storage-key="exportStorageKey"
      method="post"
      :action="providerListExport"/>

    <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>
  </div>
</template>

<script>
// component
import ProviderBatchEditDialog from '../component/ProviderBatchEditDialog.vue'
import ProviderAccount from "@src/modules/serviceProvider/serviceProviderManage/component/ProviderAccount.vue";
import AdvancedSearch from '@src/component/AdvancedSearch/index.vue';
//api
import {
  getServiceProviderInit,
  getProviderPageList,
  stopProvider,
  batchStopProvider,
  getProvideAllLabel,
  saveProviderAccount,
  deleteTenantProviderBatch,
  restoreTenantProvider,
  searchProviderConfig,
} from '@src/api/serviceProviderApi';
/* api */
import { storageGet, storageSet } from "@src/util/storage";
import Page from '@model/Page';
import { TABLE_HEIGHT_MIN } from '@src/model/const/Number';
import _ from "lodash";
import {openAccurateTab} from "@src/util/platform";
import {PageRoutesTypeEnum} from "@model/enum/PageRoutesEnum";
import { formatDate, useFormTimezone } from 'pub-bbx-utils'
import { defaultTableData } from '@src/util/table'
import { getFieldName, isSearchField } from '@service/FieldService';
import { safeNewDate } from '@src/util/time';
/* export & import */
import { providerListExport } from '@src/api/Export';
import { providerBaseImportFile, providerBaseImportTemplate, batchUpdateUrlTemplate, providerOrEngineerUpdateBatch } from '@src/api/Import';
/* enum */
import {  FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum';
import StorageKeyEnum from '@model/enum/StorageKeyEnum'

const { disposeFormListViewTime } = useFormTimezone()
const PROVIDER_LIST_KEY = 'provider_list';
const PROVIDER_PAGE_SIZE_KEY = 'provider_page_size';
const PROVIDER_ADD_AUTH  = 'provider_add_auth' // 服务商新建权限
// 支持批量编辑的字段
const PRVIDER_EDIT_FIELD = ['providerType', 'type',  'provideQuality', 'validTime', 'authorizeTask', 'authorizeProduct', 'role']
import { t } from '@src/locales'
export default {
  name: 'provider-list',
  props: {
    shareData: {
      type: Object,
      default: () => ({
        status: '1',
        hideTopTip: false
      })
    },
  },
  components: {
    ProviderBatchEditDialog,
    ProviderAccount,
    AdvancedSearch
  },
  computed: {
    // 处理时间后的列表数据
    tableData(){
      return disposeFormListViewTime(this.dataList, this.columns)
    },
    // 当前选中的服务商
    selectedIds() {
      return this.multipleSelection.map((p) => p.tenantProviderId);
    },
    batchEditProviderTemplateFields() {
      return this.columns.filter(field => PRVIDER_EDIT_FIELD.includes(field.fieldName));
    },
    // 是否是注销服务商列表
    isLogOut() {
      return this.shareData?.status === '0' || false
    },
    exportColumns() {
      const needFilterForm = ['attachment','separator','info', 'autograph', 'imageDisplay'];
      this.columns.filter(item=> !needFilterForm.includes(item.formType) && item.fieldName !== 'qualificationNames')
      .map(v => {
        v.field = v.fieldName;
        v.label = v.displayName;
        v.export = true;
      });
      return this.columns;
    }
  },
  data() {
    return {
      exportStorageKey: StorageKeyEnum.ProviderListExport,
      batchUpdateUrlTemplate, 
      providerOrEngineerUpdateBatch,
      providerListExport,
      providerBaseImportTemplate,
      providerBaseImportFile,
      defaultTableData,
      columns: [],
      selectedRole: {},
      btnsPermission: [], // 按钮权限
      deptKeyword: '',
      status:[],
      dataList: [], // 列表的数据
      listLoading: false,
      tableContainerHeight: `${TABLE_HEIGHT_MIN}px`, // 表格默认最小440px
      page: new Page(), // page 对象
      multipleSelection: [], // 勾选的数量
      label: [ { label: this.$t('serviceProvider.labelManage.tip6'), value: -1} ], // 服务商列表选择的标签
      /*账户分配参数*/
      hideTopTip: false,
      searchFieldInfo: [],
      viewportSearchModel:[],
      searchModel: {},
      inCommonUse: [],
      uploadParamObject: {
        type: 1
      }
    }
  },
  async mounted() {
    try {
      await this.recoverCommonUse(); // 读取常用条件缓存
      // 获取缓存的pagesize
      const localStorageData = await this.getLocalStorageData();
      this.page.pageSize = localStorageData[PROVIDER_PAGE_SIZE_KEY] || 10;
      // 获取表头
      this.getInitInfo();

      // 获取表格数据
      this.search();

      // 获取表单字段
      this.getProvideFields();

      let that_ = this;
      // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
      window.addEventListener('message', (event)=> {
        const {action} = event.data;
        if (action === 'shb.frame.activatedPage'){
          that_.$nextTick(()=> {
            that_.knowTableContainerHeight();
          })
        }
      });
      
      // 监听窗口变化
      window.addEventListener('resize', (event) => {
        this.debounceKnowTableContainerHeight()
      })
      
      this.$nextTick(()=> {
        this.knowTableContainerHeight()
        window.onresize = _.debounce(()=>{
          that_.knowTableContainerHeight()
        }, 500)
      })
    } catch (e) {
      console.error(e)
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.debounceKnowTableContainerHeight)
  },
  methods: {
    /** 打开富文本弹窗 */
    openRichtextVisible(row, column) {
      const richtextId = row?.formVOList?.[column.fieldName] || ''
      this.$refs?.baseViewRichTextRef?.openDialog(richtextId)
    },
    /** 导出服务商 */
    exportProcider(exportAll) {
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}${t('common.base.serviceProvider')}.xlsx`;
      if (!exportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert(t('common.base.tip.exportNoChoice'));
        ids = this.selectedIds;
      }
      this.$refs.exportPanel.open(ids, fileName);
    },
    /**打开导出弹窗 */
    openDialog(type) {
      if(type == 'importProviderList') {
        this.$refs.importModal.open();
      }else{
        this.$refs.batchUpdateDialog.openBatchUpdateCustomerDialog();
      }
    },
    /** 检测导出条数 */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.page.totalElements > max
        ? this.$t('common.base.tip.exportLimit', { max })
        : null;
    },
    /** 构建导出参数*/
    buildExportParams(checkedArr, ids) {
      let exportAll = !ids || !ids.length;

      return {
        searchModel: JSON.stringify({ ...this.buildSearchParams() }),
        exportTotal: exportAll ? this.page.total : ids.length,
        checked: checkedArr.join(','),
        idList: exportAll ? [] : ids,
        ...this.uploadParamObject
      };
    },
    /**点击搜索 */
    onSearch() {
      this.searchList();
    },
    /**点击重置 */
    handleReset() {
      this.deptKeyword = ''
      this.viewportSearchModel = [];
      this.searchList();
    },
    /** 恢复常用字段 */
     async recoverCommonUse(){
      try {
        const storageKey = 'advanced-search-commonUse';
        const data = await this.getLocalStorageData()
        this.inCommonUse = data[storageKey] || [];
      } catch (error) {
        console.error('获取常用字段 recoverCommonUse', error);
        return Promise.reject(error)
      }
    },
    /** 切换常用字段*/
    changeCommonUse({fieldName, isChecked}){
      const inCommonUseSet = new Set(this.inCommonUse)
      if(isChecked){
        inCommonUseSet.add(fieldName)
      }else {
        inCommonUseSet.delete(fieldName);
      }
      this.inCommonUse = Array.from(inCommonUseSet);
      const storageKey = 'advanced-search-commonUse';
      this.saveDataToStorage(storageKey, this.inCommonUse);
    },
    /**获取服务商表单数据 */
    async getProvideFields(){
      try {
        const res = await searchProviderConfig();
        const {code, result= [], message} = res;
        if(code == 0) {
          // 过滤隐藏字段
          const fields = result.filter(field => !field.isHidden);

          this.searchFieldInfo = this.getAdvancedFields(fields);
        }
      } catch(error) {
        console.log(error)
      }
    },
    /**处理高级搜索字段 */
    getAdvancedFields(fields) {
      const FIELD_SEARCH = [ FieldTypeMappingEnum.AuthorizeAddress, FieldTypeMappingEnum.AuthorizeProduct, FieldTypeMappingEnum.TagLabel]
     
      let advancedFields = fields.map(field => {
        // 授权区域
        if (getFieldName(field) === FieldTypeMappingEnum.AuthorizeAddress) field.formType = FieldTypeMappingEnum.Address;
        return field;
      }).filter(field => {
        const isFieldSearch = FIELD_SEARCH.includes(field.fieldName);
        return isSearchField(field) || isFieldSearch;
      });
     
      return advancedFields
    },
    /**点击高级搜索 */
    handleAdvancedSearch(searchModel = {}){
      this.searchModel = searchModel;
      this.searchList();
    },
    // 获取租户的服务商账号
    async getTenantProviderAccountData() {
      try {
        let res = await getTenantProviderAccountData();
        if(res.success) {
          this.allNum = res?.result?.allNum;
          this.assignedNum = res?.result?.assignedNum;
          this.remainNum = res?.result?.remainNum;
        }
      } catch (e) {
        console.error(e)
      }
    },

    async getAllLabel() {
      try {
        // 调接口去查询下拉标签的值
        let res = await getProvideAllLabel();
        let list = res?.data?.map(item => {
          return {
            label: item?.labelName || '',
            value: item?.id || '',
          }
        })
        list.unshift({label: this.$t('serviceProvider.labelManage.tip6'), value: -1,})
        return {
          list,
          total: res?.result?.length || 0,
          hasNextPage: false,
        }
      } catch (e) {
        console.error(e)
      }
    },

    // 获取表头数据
    async getInitInfo() {
      try {
        let res = await getServiceProviderInit();
        if(res.success && res.code === 0) {
          res.result.buttonList.forEach(item => {
            this.btnsPermission[item.type] = item.visible;
            if(item.type === 'create') storageSet(PROVIDER_ADD_AUTH, item.visible);
          });// 按钮权限
          this.columns = res?.result?.allField?.filter(item => item.isHidden != 1)?.map(item => {
            item.showTip = true
            item.show = true;
            item.tableName= 'provider'
            if(['createTime', 'updateTime'].includes(item.fieldName)){
              // 临时处理强制时间格式为dateTime
              item.formType = 'datetime'
            }
            if(item.fieldName === 'imageDisplay') item.showTip = false;
            return item;
          }) ?? [];
          // 状态
          let fieldStatus = this.columns.filter(item => item.fieldName === 'status');
          if(fieldStatus && fieldStatus.length) {
            this.status = fieldStatus[0]?.setting?.dataSource || [];
          }
          this.columns.splice(3, 0, {fieldName:'qualificationNames', displayName:t('common.label.subCertifications'), formType:'text', isSystem:1, show:true, tableName:"provider"})
          this.buildColumns();
        } else {
          this.$message.error(res.message || this.$t('serviceProvider.providerListInitError'));
        }
      } catch (e) {
        console.error(e);
      }
    },

    // 处理表头数据
    buildColumns() {
      const localStorageData = this.getLocalStorageData();
      let columnStatus = localStorageData.columnStatus || [];

      const localColumns = columnStatus
          .map((i) => (typeof i == 'string' ? { field: i, show: true } : i))
          .reduce((acc, col, currentIndex) => {
            acc[col.field] = {
              field: col,
              index: currentIndex,
            }
            return acc
          }, {});

      let providerFields = this.columns;
      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        // 有本地缓存--列表排序
        providerFields = this.buildSortFields(providerFields, localColumns);
      }

      const columns = providerFields.map((col) => { // 选择列配置 是否勾选（显示）&宽度
        let show = col.show;
        let width = col.width;

        let localField = localColumns[col.fieldName]?.field || null;
        let fixLeft = localField?.fixLeft || null;

        if (null != localField) {
          if (localField.width) {
            width = typeof localField.width == 'number'
                ? `${localField.width}px`
                : localField.width;
          }
          show = localField.show !== false;
        }
        col.show = show;
        col.width = width;
        col.minWidth = col.width || 150;
        col.type = 'column';
        col['fixLeft'] = fixLeft && 'left'
        return col;
      }).filter(item => !['separator', 'attachment', 'info', 'autograph'].includes(item.formType))

      this.columns = []
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice())
      })
    },
    searchList() {
      this.page.pageNum = 1;
      this.search();
    },
    // 获取列表数据
    async search() {
      this.listLoading = true;
      try {
        const params = this.buildSearchParams();
        let res = await getProviderPageList(params);
        if(res.success && res.code === 0) {
          let list = res?.result?.providerList?.list;
          if (!list) this.page = new Page();
          this.page.merge(res.result.providerList);
          this.dataList = list || [];
          this.matchSelected();
        }
      } catch (e) {
        console.error(e);
      } finally {
        this.listLoading = false;
      }
    },

    // 获取本地localstorage
    getLocalStorageData() {
      const dataStr = storageGet(PROVIDER_LIST_KEY, '{}');
      return JSON.parse(dataStr);
    },

    // 选择列排序
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = []

      originFields.forEach(originField => {
        let { fieldName } = originField
        let field = fieldsMap[fieldName]

        if (field) {
          let { index } = field
          fields[index] = originField
        } else {
          unsortedFields.push(originField)
        }
      })

      return fields.concat(unsortedFields)
    },

    // 构建搜索参数
    buildSearchParams() {
      let { pageNum, pageSize } = this.page;
      let data = {
        pageNum,
        pageSize,
        searchKey: this.deptKeyword,
        status: this.shareData?.status,
        tagId: this.shareData?.tagId
      }
      if(this.label?.[0]?.value !== -1) data.label = this.label?.[0]?.value
      return { ...data, ...this.searchModel };
    },

    // 保存数据到本地localstorage
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet(PROVIDER_LIST_KEY, JSON.stringify(data));
    },

    // 保存选择列配置到本地
    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null

      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.fieldName,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },

    // 保存选择列配置
    saveColumnStatus(event) {
      let columns = event.data || []

      this.columns = []
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.saveColumnStatusToStorage()
      })
      this.$message.success(this.$t('common.base.saveSuccess'));
    },

    handleSelection(selection){
      let tv = [];

      tv = this.multipleSelection.filter((ms) =>
          this.dataList.every((c) => c.tenantProviderId !== ms.tenantProviderId)
      );

      this.multipleSelection = _.uniqWith([...tv, ...selection], _.isEqual);
    },

    // 点击选择列
    handleSelectColumn() {
      this.$refs.advanced?.open(this.columns);
    },

    // 页码跳转
    handlePageJump(pageNum) {
      this.page.pageNum = pageNum;
      this.search();
    },

    // 页数修改
    handleSizeChange(pageSize) {
      this.saveDataToStorage(PROVIDER_PAGE_SIZE_KEY, pageSize);
      this.page.pageSize = pageSize;
      this.page.pageNum = 1;
      // 列表查询
      this.search();
    },

    gotoUrl(type, key = '', params = '') {
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type:PageRoutesTypeEnum[type],
        key,
        params,
        fromId
      })
    },

    // 获取服务商状态
    getStatus(status) {
      return this.status.filter(item => item && item.value === status)[0]?.text || ''
    },
    
    // 授权区域
    getAreas(areas) {
      if(Array.isArray(areas)) return areas.map(item => item && item.all).join('、')
    },

    // 授权工单类型&授权产品类型
    getAuthorize(authorizes) {
      if(Array.isArray(authorizes)) return authorizes.map(item => item && item.name).join('；')
    },

    // 恢复服务商
    async recoveryProvider(row) {
      try {
        await this.$confirm(this.$t('serviceProvider.recoverProvider.title'), this.$t('serviceProvider.recoverProvider.message'));
        let res = await restoreTenantProvider({tenantProviderId: row.tenantProviderId});
        this.$message({
          type: res.success ? 'success' : 'error',
          message: res.success ? this.$t('serviceProvider.recoverProvider.success') : res.message,
          showClose: true,
          duration: 2000,
        });
        this.resetSearch();
      } catch (e) {
        console.error(e)
      }
    },

    // 删除服务商
    async deleteProvider(row) {
      await this.$confirm(this.$t('serviceProvider.accountTip.tip17'), this.$t('serviceProvider.accountTip.tip16'));
      let { success, message } = await deleteTenantProviderBatch({ids: [row.tenantProviderId]});
      this.$message({
        type: success ? 'success' : 'error',
        message: success ? this.$t('common.base.deleteSuccess') : message,
        showClose: true,
        duration: 2000,
      });
      this.resetSearch();
    },

    // 注销服务商
    async stopProvider(row) {
      try {
        if(row.status === '0') { // 服务商已注销
          return this.$message.warning({
            message: this.$t('serviceProvider.providerIsLogout'),
            showClose: true,
            duration: 2000,
          });
        }
        await this.$confirm(this.$t('serviceProvider.providerLogout'), this.$t('serviceProvider.logoutTip'));
        let res = await stopProvider({tenantProviderId: row.tenantProviderId});
        this.$message({
          type: res.success ? 'success' : 'error',
          message: res.success ? this.$t('common.base.logoutSuccess') : res.message,
          showClose: true,
          duration: 2000,
        });
        // TODO 刷新整个页面，注销完成以后返回到服务商树下面
        this.resetSearch();
        this.$emit('refresh');
      } catch (e) {
        console.error(e);
      }
    },

    //批量注销服务商
    async batchStopProvider() {
      if(!this.multipleSelection.length) {
        this.$message({
          message: this.$t('common.placeholder.selectServiceProvider'),
          type: 'warning',
        });
      } else {
        try {
          await this.$confirm(this.$t('serviceProvider.providerLogout'), this.$t('serviceProvider.logoutTip'));
          //调用接口去注销
          let ids = this.multipleSelection.map(item => item.tenantProviderId);
          let res = await batchStopProvider({ids});
          this.$message({
            type: res.success ? 'success' : 'error',
            message: res.success ? this.$t('common.base.batchLogoutSuccess') : res.message,
            showClose: true,
            duration: 2000,
          });
          this.multipleSelection = []
          this.resetSearch();
          this.$emit('refresh');
        } catch (e) {
          console.error(e);
        }
      }
    },

    //批量编辑服务商
    editProviders() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: this.$t('common.placeholder.selectServiceProvider'),
          type: 'warning',
          showClose: true,
          duration: 1500,
        });
      } else {
        // 打开弹窗编辑服务商
        this.$refs.providerBatchEditDialog.open();
      }
    },

    // 批量分配
    bulkAllocation(isBulk = false, tenantProviderId = '') {
      if(isBulk && !this.multipleSelection.length) {
        this.$message({
          message: this.$t('common.placeholder.selectServiceProvider'),
          type: 'warning',
        });
      } else {
        let tenantProviderIdList = isBulk ? this.selectedIds : [tenantProviderId];
        this.$refs?.providerAccount?.openDialog(tenantProviderIdList, isBulk)
      }
    },

    // 重置
    resetSearch() {
      this.page.pageNum = 1;
      // 账号数量查询
      //this.getTenantProviderAccountData();
      // 列表查询
      this.search();
    },

    // 表格高度计算
    knowTableContainerHeight(){
      let min = TABLE_HEIGHT_MIN; // 表格默认最小440
      try {
        let window_ = window.innerHeight;
        let header = (this.$refs.tableHeaderContainer?.offsetHeight + 16)|| 0; // 按钮选择列高度
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0; // 分页高度
        let accountTip = (this.$refs.tableAccountTip?.offsetHeight + 12)  || 0; // 账户分配信息提示高度
        let topTip = this.shareData?.hideTopTip ? 0 : 48; // 最上面审批账户提示信息高度
        let proTab = document.querySelector('.main-tab .el-tabs__nav-scroll')?.offsetHeight || 0; // tab高度
        min = window_ - header * 1  - footer * 1 - accountTip - proTab - topTip - 16 * 3 - 40 - 20 - 12; // 16：整个页面的上下两个padding和一个搜索框距离表格的距离；
        min = min + 12;
        min = min > TABLE_HEIGHT_MIN ? min : TABLE_HEIGHT_MIN;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    debounceKnowTableContainerHeight: _.debounce(function() {
      this.knowTableContainerHeight();
    }, 500),
    // 清空选择框
    toggleClearSelection() {
      this.multipleSelection = [];
      this.$refs.tableRef.clearSelection();
    },

    // 把选中的匹配出来
    matchSelected() {
      if (this.multipleSelection.length) {
        this.$nextTick(() => {
          this.dataList.forEach(item => {
            if(this.multipleSelection.some(v=> item.tenantProviderId === v.tenantProviderId)){
              this.$refs.tableRef.toggleRowSelection(item, true);
            }
          });
        })
      }
    },

    //tab切换需求重置表格高度和刷新数据
    refreshProvider() {
      this.search();
      this.$nextTick(() => {
        this.knowTableContainerHeight();
      })
    },

    //图片查看
    previewImg (url, urls = []) {
      if(typeof urls !== 'object'){
        urls = []
      }
      this.$previewElementImg(url, urls);
    },
  },
  watch: {
    shareData:{
      deep: true,
      handler(val) {
        if(val.hideTopTip) {
          this.knowTableContainerHeight();// 监听头部提示是否隐藏，隐藏的话调用
        }
        this.search();
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.provider-list {
  height: 100%;
  overflow: auto;
  border-radius: 4px;
  padding: 0;
  background: white;
  &-main {
    background: white;
    padding: 0 12px;
    &-search {
      margin-top: 16px;
      justify-content: space-between;
    }
    .flexEnd {
      justify-content: end;
    }
    .biz-form-remote-select {
      width: 120px;
    }
    .search-input {
      width: 250px;
    }
  }
  .c-primary {
    color: $color-primary;
  }
  .goods-img-list img {
    width: 32px;
    height: 32px;
  }
  .advanced-search-wrap {
    margin: 0 12px;
  }
}
</style>
<style lang="scss">
.label-search {
  min-width: 180px;
  max-width: 240px;
}
.el-dropdown-provider {
  width: 100px;
}
</style>